package com.youshang.xinqiang;

import java.util.ArrayList;
import java.util.List;

public class q1n {
    private static final int MAX_DISTANCE = 10;

    private static int m = 10;
    private static int n = 9;

    //每s毫秒若干新角色会在生成点被创建出来。
    private static int s = 100;

    private static List<Character> characters = new ArrayList<>();

    public static void main(String[] args) {
        // Generate initial characters
        generateCharacters();

        long startTime = System.currentTimeMillis();

        while (System.currentTimeMillis() - startTime < 10000) {
            moveCharacters();
            generateCharacters();
            try {
                Thread.sleep(s);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int totalMoves = 0;
        for (Character character : characters) {
            totalMoves += character.getMoveCount();
        }

        System.out.println("Total moves: " + totalMoves);
    }

    private static void generateCharacters() {
        for (int i = 0; i < n; i++) {
            int x = (int) (Math.random() * m);
            int y = (int) (Math.random() * m);
            characters.add(new Character(x, y));
        }
    }

    private static void moveCharacters() {
        List<Character> toRemove = new ArrayList<>();

        for (Character character : characters) {
            if (character.isAlive()) {
                character.move();
                if (!character.isValidMove()) {
                    toRemove.add(character);
                }
            }
        }

        characters.removeAll(toRemove);
    }

    static class Character {
        private int x;
        private int y;
        private int targetX;
        private int targetY;
        private int moveCount;

        public Character(int x, int y) {
            this.x = x;
            this.y = y;
            chooseRandomTarget();
        }

        public void move() {
            int dx = Integer.compare(targetX, x);
            int dy = Integer.compare(targetY, y);

            if (dx != 0) {
                x += dx;
            }

            if (dy != 0) {
                y += dy;
            }

            moveCount++;
        }

        public boolean isValidMove() {
            return x >= 0 && x < m && y >= 0 && y < m;
        }

        public boolean isAlive() {
            return isValidMove();
        }

        public int getMoveCount() {
            return moveCount;
        }

        private void chooseRandomTarget() {
            int dx = (int) (Math.random() * (2 * MAX_DISTANCE + 1)) - MAX_DISTANCE;
            int dy = (int) (Math.random() * (2 * MAX_DISTANCE + 1)) - MAX_DISTANCE;
            targetX = Math.max(0, Math.min(m - 1, x + dx));
            targetY = Math.max(0, Math.min(m - 1, y + dy));
        }
    }
}
